package microservices.spring_cloud_server.rest;

import java.lang.reflect.Method;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import microservices.spring_cloud_server.annontation.Permission;

@Aspect
@Component
public class PermissionAop {
	@Pointcut("@annotation(microservices.spring_cloud_server.annontation.Permission)")
	public void permissionPointcut() {
	}

	@Around(value = "permissionPointcut()")
	public Object hasPermission(ProceedingJoinPoint pjp) throws Throwable {
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method method = methodSignature.getMethod();
		Permission permission = method.getAnnotation(Permission.class);
		String requestPermission = permission.requestPermission();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String token = request.getHeader("Authorization").substring(7);
		Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
		ArrayList<?> hasPermission = (ArrayList<?>) claims.get("permission");
		System.out.println(hasPermission);
		System.out.println(requestPermission);
		if (hasPermission.contains(requestPermission)) {
			Object obj = pjp.proceed();
			return obj;
		} else {
			throw new RuntimeException("没有" + requestPermission + "权限！");
		}
	}

}
